<template>
  <div class="dashboard">
    <!-- 顶部数据统计 -->
    <el-row :gutter="20" class="data-statistics">
      <el-col :span="6" v-for="(item, index) in statistics" :key="index">
        <div class="statistic-card">
          <div class="statistic-icon" :style="{ backgroundColor: item.color + '20', color: item.color }">
            <svg-icon :icon-class="item.icon" />
          </div>
          <div class="statistic-info">
            <div class="statistic-value">{{ item.value }}</div>
            <div class="statistic-label">{{ item.label }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 中部配置区域 -->
    <el-row :gutter="20" class="config-section">
      <el-col :span="24">
        <div class="config-card">
          <div class="config-header">
            <h2>平台配置管理</h2>
            <p>管理各个平台的配置信息</p>
          </div>
          
          <!-- 扑克牌式平台配置展示 -->
          <div class="platform-cards">
            <!-- 租号玩配置 -->
            <div class="platform-card-wrapper">
              <el-card 
                class="platform-card" 
                :class="{ 'active': zhwOpen === '1' }"
                shadow="hover"
              >
                <div class="platform-header">
                  <div class="platform-title">
                    <h3>租号玩</h3>
                  </div>
                  <div class="platform-switch">
                    <el-switch
                      v-model="zhwOpen"
                      active-value="1"
                      inactive-value="0"
                      active-text="已开通"
                      inactive-text="未开通"
                    />
                  </div>
                </div>
                
                <div class="platform-body">
                  <el-form :model="platCfg.zhwCfg" label-width="80px" class="config-form">
                    <el-form-item label="商户ID" :rules="zhwRules.merId">
                      <el-input v-model="platCfg.zhwCfg.merId" placeholder="请输入商户ID" />
                    </el-form-item>
                    <el-form-item label="授权码" :rules="zhwRules.authCode">
                      <el-input 
                        v-model="platCfg.zhwCfg.authCode" 
                        :type="zhwPasswordVisible ? 'text' : 'password'"
                        placeholder="请输入授权码"
                      >
                        <template #append>
                          <el-button @click="zhwPasswordVisible = !zhwPasswordVisible">
                            <svg-icon :icon-class="zhwPasswordVisible ? 'eye-open' : 'eye'" />
                          </el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label="管理后台">
                      <div class="bind-container">
                        <el-button 
                          type="primary" 
                          @click="openZhwLogin"
                        >
                          绑定管理后台
                        </el-button>
                        <span class="bind-status" :class="{ 'bound': platCfg.zhwCfg?.backCookie && platCfg.zhwCfg?.backCookie.trim() !== '' }">
                          {{ platCfg.zhwCfg?.backCookie && platCfg.zhwCfg?.backCookie.trim() !== '' ? '已绑定' : '未绑定或已失效' }}
                        </span>
                      </div>
                    </el-form-item>
                    <div class="form-placeholder"></div>
                  </el-form>
                </div>
                
                <div class="platform-footer">
                  <div class="error-message" v-if="platCfg.zhwCfg.errMsg">
                    <i class="el-icon-warning"></i>
                    <span>{{ platCfg.zhwCfg.errMsg }}</span>
                  </div>
                  <div class="error-placeholder" v-else></div>
                  <div class="save-button">
                    <el-button 
                      type="primary" 
                      size="default" 
                      @click="savePlatformConfig('zhw')"
                      :loading="saveLoadingZhw"
                    >
                      保存配置
                    </el-button>
                  </div>
                </div>
              </el-card>
            </div>
            
            <!-- 转转配置 -->
            <div class="platform-card-wrapper">
              <el-card 
                class="platform-card" 
                :class="{ 'active': zzOpen === '1' }"
                shadow="hover"
              >
                <div class="platform-header">
                  <div class="platform-title">
                    <h3>转转</h3>
                  </div>
                  <div class="platform-switch">
                    <el-switch
                      v-model="zzOpen"
                      active-value="1"
                      inactive-value="0"
                      active-text="已开通"
                      inactive-text="未开通"
                    />
                  </div>
                </div>
                
                <div class="platform-body">
                  <el-form :model="platCfg.zzCfg" label-width="80px" class="config-form">
                    <el-form-item label="商户ID" :rules="zzRules.merId">
                      <el-input v-model="platCfg.zzCfg.merId" placeholder="请输入商户ID" />
                    </el-form-item>
                    <el-form-item label="授权码" :rules="zzRules.authCode">
                      <el-input 
                        v-model="platCfg.zzCfg.authCode" 
                        :type="zzPasswordVisible ? 'text' : 'password'"
                        placeholder="请输入授权码"
                      >
                        <template #append>
                          <el-button @click="zzPasswordVisible = !zzPasswordVisible">
                            <svg-icon :icon-class="zzPasswordVisible ? 'eye-open' : 'eye'" />
                          </el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                    <div class="form-help" @click="showZZQrCode">
                      <span class="help-text">如何获取授权码？</span>
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="点击查看获取方式"
                        placement="top"
                      >
                        <i class="el-icon-question help-icon"></i>
                      </el-tooltip>
                    </div>
                    <div class="form-placeholder"></div>
                  </el-form>
                </div>
                
                <div class="platform-footer">
                  <div class="error-message" v-if="platCfg.zzCfg.errMsg">
                    <i class="el-icon-warning"></i>
                    <span>{{ platCfg.zzCfg.errMsg }}</span>
                  </div>
                  <div class="error-placeholder" v-else></div>
                  <div class="save-button">
                    <el-button 
                      type="primary" 
                      size="default" 
                      @click="savePlatformConfig('zz')"
                      :loading="saveLoadingZz"
                    >
                      保存配置
                    </el-button>
                  </div>
                </div>
              </el-card>
            </div>
            
            <!-- U号租配置 -->
            <div class="platform-card-wrapper">
              <el-card 
                class="platform-card" 
                :class="{ 'active': uhzOpen === '1' }"
                shadow="hover"
              >
                <div class="platform-header">
                  <div class="platform-title">
                    <h3>U号租</h3>
                  </div>
                  <div class="platform-switch">
                    <el-switch
                      v-model="uhzOpen"
                      active-value="1"
                      inactive-value="0"
                      active-text="已开通"
                      inactive-text="未开通"
                    />
                  </div>
                </div>
                
                <div class="platform-body">
                  <el-form :model="platCfg.uhzCfg" label-width="80px" class="config-form">
                    <el-form-item label="商户ID" :rules="uhzRules.merId">
                      <el-input v-model="platCfg.uhzCfg.merId" placeholder="请输入商户ID" />
                    </el-form-item>
                    <el-form-item label="授权码" :rules="uhzRules.authCode">
                      <el-input 
                        v-model="platCfg.uhzCfg.authCode" 
                        :type="uhzPasswordVisible ? 'text' : 'password'"
                        placeholder="请输入授权码"
                      >
                        <template #append>
                          <el-button @click="uhzPasswordVisible = !uhzPasswordVisible">
                            <svg-icon :icon-class="uhzPasswordVisible ? 'eye-open' : 'eye'" />
                          </el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label="管理后台">
                      <div class="bind-container">
                        <el-button
                            type="primary"
                            @click="openZhwLogin"
                        >
                          绑定管理后台
                        </el-button>
                        <span class="bind-status" :class="{ 'bound': platCfg.uhzCfg?.backCookie && platCfg.uhzCfg?.backCookie.trim() !== '' }">
                          {{ platCfg.uhzCfg?.backCookie && platCfg.uhzCfg?.backCookie.trim() !== '' ? '已绑定' : '未绑定或已失效' }}
                        </span>
                      </div>
                    </el-form-item>
                    <div class="form-placeholder"></div>
                  </el-form>
                </div>
                
                <div class="platform-footer">
                  <div class="error-message" v-if="platCfg.uhzCfg.errMsg">
                    <i class="el-icon-warning"></i>
                    <span>{{ platCfg.uhzCfg.errMsg }}</span>
                  </div>
                  <div class="error-placeholder" v-else></div>
                  <div class="save-button">
                    <el-button 
                      type="primary" 
                      size="default" 
                      @click="savePlatformConfig('uhz')"
                      :loading="saveLoadingUhz"
                    >
                      保存配置
                    </el-button>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 转转二维码弹窗 -->
    <el-dialog
        v-model="zzQrCodeVisible"
        width="350px"
        center
    >
      <div class="qr-code-wrapper">
        <img :src="zzQrCodeUrl" alt="转转授权二维码" class="qr-code-img" />
        <p class="qr-code-tip">请扫描上方二维码登录后复制授权码</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { getPlatCfg, savePlatCfg } from '@/api/custom/index'
import zzAuthImage from '@/assets/images/zz-auth.png'

// Tauri API导入
import { invoke } from '@tauri-apps/api/core'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
import { listen } from '@tauri-apps/api/event';
import {listAccountInfo} from "@/api/custom/hpjy.js";

const userStore = useUserStore()

// 绑定渠道数计算属性
const boundChannels = computed(() => {
  let count = 0
  if (zhwOpen.value === '1') count++
  if (zzOpen.value === '1') count++
  if (uhzOpen.value === '1') count++
  return count
})

// 统计数据
const statistics = ref([
  { label: '绑定渠道数', value: 0, icon: 'link', color: '#409EFF' },
  { label: '总货架数', value: 0, icon: 'guide', color: '#67C23A' },
  { label: '上架货架数', value: 0, icon: 'nested', color: '#E6A23C' },
  { label: '出租中货架数', value: 0, icon: 'shopping', color: '#F56C6C' }
])

// 配置数据
const platCfg = reactive({
  bhId: undefined,
  zhwCfg: {
    merId: '',
    authCode: '',
    backCookie: '',
    errMsg: ''
  },
  zzCfg: {
    merId: '',
    authCode: '',
    errMsg: ''
  },
  uhzCfg: {
    merId: '',
    authCode: '',
    backCookie: '',
    errMsg: ''
  }
})

// 表单验证规则
const zhwRules = computed(() => {
  const rules = {}
  if (zhwOpen.value === '1') {
    rules.merId = [{ required: true, message: '租号玩已开通，商户ID不能为空', trigger: 'blur' }]
    rules.authCode = [{ required: true, message: '租号玩已开通，授权码不能为空', trigger: 'blur' }]
  }
  return rules
})

const zzRules = computed(() => {
  const rules = {}
  if (zzOpen.value === '1') {
    rules.merId = [{ required: true, message: '转转已开通，商户ID不能为空', trigger: 'blur' }]
    rules.authCode = [{ required: true, message: '转转已开通，授权码不能为空', trigger: 'blur' }]
  }
  return rules
})

const uhzRules = computed(() => {
  const rules = {}
  // U号租的验证规则：只有在开通状态下才需要验证
  if (uhzOpen.value === '1') {
    const uhzHasMerIdAndAuthCode = platCfg.uhzCfg.merId && platCfg.uhzCfg.authCode
    const uhzHasBackCookie = platCfg.uhzCfg.backCookie
    
    if (!uhzHasMerIdAndAuthCode && !uhzHasBackCookie) {
      rules.merId = [{ required: true, message: 'U号租商户ID和授权码必填，或者管理后台必填', trigger: 'blur' }]
      rules.authCode = [{ required: true, message: 'U号租商户ID和授权码必填，或者管理后台必填', trigger: 'blur' }]
    }
  }
  return rules
})

// 开通状态
const zhwOpen = ref('0')
const zzOpen = ref('0')
const uhzOpen = ref('0')

// 密码可见状态
const zhwPasswordVisible = ref(false)
const zzPasswordVisible = ref(false)
const uhzPasswordVisible = ref(false)

// UI状态
const saveLoadingZhw = ref(false)
const saveLoadingZz = ref(false)
const saveLoadingUhz = ref(false)

// 二维码弹窗相关
const zzQrCodeVisible = ref(false)
const zzQrCodeUrl = ref('') // 这里应该是实际的二维码图片URL

// 定时器
const statisticsTimer = ref(null)

// 更新统计数据
const updateStatistics = () => {
  statistics.value[0].value = boundChannels.value
  // 其他统计数据会通过定时器更新
}

// 监听绑定渠道数变化
watch(boundChannels, () => {
  updateStatistics()
})

// 获取平台配置
const fetchPlatCfg = async () => {
  try {
    const res = await getPlatCfg()
    
    // 检查响应是否有效
    if (res && typeof res === 'object' && res.code === 200) {
      platCfg.bhId = res.data.bhId
      platCfg.zhwCfg = res.data.zhwCfg || platCfg.zhwCfg
      platCfg.zzCfg = res.data.zzCfg || platCfg.zzCfg
      platCfg.uhzCfg = res.data.uhzCfg || platCfg.uhzCfg
      zhwOpen.value = res.data.zhwOpen || '0'
      zzOpen.value = res.data.zzOpen || '0'
      uhzOpen.value = res.data.uhzOpen || '0'
      
      // 更新统计数据
      updateStatistics()
    } else if (res && typeof res === 'object' && res.code !== 200) {
      // 处理业务错误
      const errorMsg = res.msg ? res.msg : '错误代码: ' + res.code
      ElMessage.error('获取平台配置失败: ' + errorMsg)
    } else {
      ElMessage.error('获取平台配置失败: 服务器响应格式不正确')
    }
  } catch (err) {
    // 处理网络错误或其他异常
    const errorMsg = err.message ? err.message : '网络错误或服务器无响应'
    ElMessage.error('获取平台配置失败: ' + errorMsg)
  }
}

// 获取货架统计数据
const fetchShelfStatistics = async () => {
  try {
    const res = await invoke('shelf_statistics')
    
    if (res && typeof res === 'object' && res.code === 200) {
      statistics.value[1].value = res.data.totalCount
      statistics.value[2].value = res.data.onShelfCount
      statistics.value[3].value = res.data.rentedCount
    }
  } catch (err) {
    console.error('获取货架统计数据失败:', err)
  }
}

// 检查平台配置是否发生变化
const checkPlatformConfigChanged = async () => {
  let hasChanged = false;
  // 获取原始配置数据用于比较
  const originalData = await getPlatCfg();
  
  if (originalData && originalData.data) {
    const originalCfg = originalData.data;
    
    // 检查租号玩配置是否发生变化
    if (platCfg.zhwCfg.merId !== originalCfg.zhwCfg.merId || 
        platCfg.zhwCfg.authCode !== originalCfg.zhwCfg.authCode ||
        platCfg.zhwCfg.backCookie !== originalCfg.zhwCfg.backCookie ||
        zhwOpen.value !== originalCfg.zhwOpen) {
      hasChanged = true;
    }
    
    // 检查转转配置是否发生变化
    if (platCfg.zzCfg.merId !== originalCfg.zzCfg.merId || 
        platCfg.zzCfg.authCode !== originalCfg.zzCfg.authCode ||
        zzOpen.value !== originalCfg.zzOpen) {
      hasChanged = true;
    }
    
    // 检查U号租配置是否发生变化
    if (platCfg.uhzCfg.merId !== originalCfg.uhzCfg.merId || 
        platCfg.uhzCfg.authCode !== originalCfg.uhzCfg.authCode ||
        platCfg.uhzCfg.backCookie !== originalCfg.uhzCfg.backCookie ||
        uhzOpen.value !== originalCfg.uhzOpen) {
      hasChanged = true;
    }
  }
  
  console.log(hasChanged ? '1' : '0');
  return hasChanged;
}

// 保存单个平台配置
const savePlatformConfig = async (platform) => {
  try {
    // 根据平台设置对应的loading状态
    switch (platform) {
      case 'zhw':
        saveLoadingZhw.value = true
        break
      case 'zz':
        saveLoadingZz.value = true
        break
      case 'uhz':
        saveLoadingUhz.value = true
        break
    }
    
    // 表单验证
    let isValid = true
    let errorMessage = ''
    
    switch (platform) {
      case 'zhw':
        if (zhwOpen.value === '1') {
          if (!platCfg.zhwCfg.merId) {
            isValid = false
            errorMessage = '租号玩已开通，商户ID不能为空'
          } else if (!platCfg.zhwCfg.authCode) {
            isValid = false
            errorMessage = '租号玩已开通，授权码不能为空'
          }
        }
        break
      case 'zz':
        if (zzOpen.value === '1') {
          if (!platCfg.zzCfg.merId) {
            isValid = false
            errorMessage = '转转已开通，商户ID不能为空'
          } else if (!platCfg.zzCfg.authCode) {
            isValid = false
            errorMessage = '转转已开通，授权码不能为空'
          }
        }
        break
      case 'uhz':
        // 只有在开通状态下才需要验证
        if (uhzOpen.value === '1') {
          const uhzHasMerIdAndAuthCode = platCfg.uhzCfg.merId && platCfg.uhzCfg.authCode
          const uhzHasBackCookie = platCfg.uhzCfg.backCookie
          if (!uhzHasMerIdAndAuthCode && !uhzHasBackCookie) {
            isValid = false
            errorMessage = 'U号租商户ID和授权码必填，或者管理后台必填'
          }
        }
        break
    }
    
    if (!isValid) {
      ElMessage.error(errorMessage)
      // 重置对应的loading状态
      switch (platform) {
        case 'zhw':
          saveLoadingZhw.value = false
          break
        case 'zz':
          saveLoadingZz.value = false
          break
        case 'uhz':
          saveLoadingUhz.value = false
          break
      }
      return
    }
    
    // 检查平台配置是否发生变化
    const hasChanged =await checkPlatformConfigChanged();
    
    // 构造要保存的数据（不包含bhId，后端会从安全上下文中获取）
    const data = {
      zhwCfg: platCfg.zhwCfg,
      zzCfg: platCfg.zzCfg,
      uhzCfg: platCfg.uhzCfg,
      zhwOpen: zhwOpen.value,
      zzOpen: zzOpen.value,
      uhzOpen: uhzOpen.value
    }
    
    const res = await savePlatCfg(data)
    
    // 检查保存是否成功
    if (res && typeof res === 'object' && res.code === 200) {
      ElMessage.success('保存成功')
      // 保存成功后重新获取最新配置
      if(hasChanged){
        console.log("同步货架列表")
        await listAccountInfo({},"2")
      }
      await fetchPlatCfg()
    } else if (res && typeof res === 'object' && res.code !== 200) {
      // 处理业务错误
      const errorMsg = res.msg ? res.msg : '错误代码: ' + res.code
      ElMessage.error('保存失败: ' + errorMsg)
    } else {
      ElMessage.error('保存失败: 服务器响应格式不正确')
    }
  } catch (err) {
    const errorMsg = err.message ? err.message : '网络错误或服务器无响应'
    ElMessage.error('保存配置失败: ' + errorMsg)
  } finally {
    // 重置对应的loading状态
    switch (platform) {
      case 'zhw':
        saveLoadingZhw.value = false
        break
      case 'zz':
        saveLoadingZz.value = false
        break
      case 'uhz':
        saveLoadingUhz.value = false
        break
    }
  }
}

// 显示转转二维码
const showZZQrCode = () => {
  zzQrCodeVisible.value = true
  // 使用导入的图片
  zzQrCodeUrl.value = zzAuthImage
}

// 打开租号玩登录页面
// 修改后的 openZhwLogin 函数
const openZhwLogin = async () => {
  ElMessage.error('功能暂未实现');
  return;
  try {
    console.log('开始执行登录窗口逻辑');
    const loginUrl = 'https://zu.zuhaowan.com/#/login?callback=tauri://login-callback';
    console.log('登录URL:', loginUrl);

    // 先尝试获取已存在的窗口
    let existingWindow = await WebviewWindow.getByLabel('zhw-login-window');

    if (existingWindow) {
      try {
        // 检查窗口是否已关闭
        const isClosed = await existingWindow.isClosed();
        if (!isClosed) {
          await existingWindow.show();
          await existingWindow.setFocus();
          console.log('已有窗口已显示并获取焦点');
          return;
        }
      } catch (err) {
        console.warn('操作已有窗口失败，准备创建新窗口:', err);
      }
    }

    // 创建新窗口
    await createNewWindow(loginUrl);
  } catch (err) {
    console.error('登录逻辑异常:', err);
    ElMessage.error(`操作失败：${err.message || '未知错误'}`);
  }
};

// 优化后的 createNewWindow 函数
const createNewWindow = async (loginUrl) => {
  try {
    const loginWindow = new WebviewWindow('zhw-login-window', {
      url: loginUrl,
      title: '租号玩登录',
      width: 800,
      height: 600,
      resizable: true,
      center: true,
      visible: false,
      decorations: true
    });

    console.log('登录窗口实例创建成功，窗口标识:', loginWindow.label);

    // 监听窗口创建错误
    loginWindow.once('tauri://error', function (e) {
      console.error('登录窗口创建失败:', e);
      ElMessage.error('登录窗口创建失败: ' + (e.payload || e.message || '未知错误'));
    });

    // 监听窗口创建完成事件
    loginWindow.once('tauri://created', async () => {
      console.log('登录窗口创建完成，准备显示');
      try {
        await loginWindow.show();
        await loginWindow.setFocus();
        console.log('窗口已显示并获取焦点');

        // 延迟注入脚本，确保webview已完全加载
        setTimeout(async () => {
          try {
            // 获取webview实例
            const webview = loginWindow.webview;
            if (webview && typeof webview.executeJavaScript === 'function') {
              // 注入脚本监听URL变化
              await webview.executeJavaScript(`
                // 保存原始函数
                const originalPushState = history.pushState;
                const originalReplaceState = history.replaceState;

                // 重写history API
                history.pushState = function(state, title, url) {
                  console.log('History pushState: ', url);
                  if (url && url.includes('tauri://login-callback')) {
                    window.__TAURI__.event.emit('navigation_callback', { url: url });
                  }
                  return originalPushState.apply(this, arguments);
                };

                history.replaceState = function(state, title, url) {
                  console.log('History replaceState: ', url);
                  if (url && url.includes('tauri://login-callback')) {
                    window.__TAURI__.event.emit('navigation_callback', { url: url });
                  }
                  return originalReplaceState.apply(this, arguments);
                };

                // 监听hash变化
                window.addEventListener('hashchange', function() {
                  console.log('Hash changed: ', location.href);
                  if (location.href.includes('tauri://login-callback')) {
                    window.__TAURI__.event.emit('navigation_callback', { url: location.href });
                  }
                });

                // 监听消息事件（备用方案）
                window.addEventListener('message', function(event) {
                  if (event.data && event.data.type === 'navigation_callback') {
                    window.__TAURI__.event.emit('navigation_callback', { url: event.data.url });
                  }
                });

                console.log('导航监听脚本已注入');
              `);

              console.log('已成功注入导航监听脚本');
            }
          } catch (err) {
            console.warn('注入脚本失败:', err);
          }
        }, 1000);
      } catch (err) {
        console.error('窗口显示流程报错:', err);
        ElMessage.warning('登录窗口显示失败，请检查系统权限');
      }
    });

    // 监听导航事件
    const unlistenNav = await loginWindow.listen('tauri://navigation', (event) => {
      console.log('捕获到导航事件，URL:', event.payload.url);
      handleLoginCallback(event.payload.url, loginWindow, unlistenNav);
    });

    // 监听来自Webview的自定义事件
    const unlistenCustom = await listen('navigation_callback', (event) => {
      console.log('捕获到自定义导航回调，URL:', event.payload.url);
      handleLoginCallback(event.payload.url, loginWindow, unlistenCustom);
    });

    return loginWindow;
  } catch (err) {
    console.error('创建新窗口时出错:', err);
    ElMessage.error('窗口创建失败：' + (err.message || '未知错误'));
    throw err;
  }
};

// 优化后的 handleLoginCallback 函数
const handleLoginCallback = async (url, loginWindow, unlisten) => {
  console.log('开始处理登录回调，URL:', url);

  if (url.startsWith('tauri://login-callback')) {
    console.log('捕获到登录回调URL');

    try {
      // 使用URL对象正确解析参数
      const urlObj = new URL(url);
      const backCookie = urlObj.searchParams.get('cookie');
      console.log('解析到的cookie:', backCookie);

      if (backCookie) {
        // 假设 platCfg 是全局对象
        platCfg.zhwCfg.backCookie = backCookie;
        ElMessage.success('登录成功');
      } else {
        ElMessage.error('未获取到登录信息');
      }

      // 登录成功后主动关闭窗口
      try {
        await loginWindow.close();
        console.log('登录窗口已关闭');
      } catch (e) {
        console.warn('关闭窗口失败:', e);
      }

      // 清理监听器
      try {
        if (typeof unlisten === 'function') {
          unlisten();
          console.log('事件监听器已清理');
        }
      } catch (e) {
        console.warn('清理监听器失败:', e);
      }
    } catch (parseError) {
      console.error('解析URL参数时出错:', parseError);
      ElMessage.error('解析登录信息失败');
    }
  } else {
    console.log('非登录回调URL，跳过处理');
  }
};

onMounted(() => {
  fetchPlatCfg()
  
  // 立即获取一次货架统计数据
  fetchShelfStatistics()
  
  // 每5秒刷新一次货架统计数据
  statisticsTimer.value = setInterval(() => {
    fetchShelfStatistics()
  }, 5000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (statisticsTimer.value) {
    clearInterval(statisticsTimer.value)
  }
})
</script>

<style lang='scss' scoped>
.dashboard-editor-container {
  padding: 22px;
  background-color: transparent;
  position: relative;
  
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, rgba(245, 247, 250, 0.7) 0%, rgba(228, 237, 249, 0.7) 100%);
    border-radius: 15px;
    z-index: -1;
  }
}

.data-statistics {
  margin-bottom: 25px;
  
  .el-col {
    margin-bottom: 25px;
  }
  
  .statistic-card {
    border-radius: 15px;
    overflow: hidden;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    background: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.5);
    height: 120px;
    display: flex;
    align-items: center;
    padding: 20px;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 12px 25px rgba(0, 0, 0, 0.12);
    }
    
    .statistic-icon {
      width: 70px;
      height: 70px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
      flex-shrink: 0;
      
      i {
        font-size: 32px;
        color: white;
      }
    }
    
    .statistic-content {
      flex: 1;
      
      .statistic-title {
        font-size: 15px;
        color: #78909c;
        margin-bottom: 8px;
        font-weight: 500;
      }
      
      .statistic-value {
        font-size: 26px;
        font-weight: 700;
        color: #263238;
      }
    }
  }
  
  // 不同颜色的主题
  .users {
    .statistic-icon {
      background: linear-gradient(120deg, #29b6f6, #0288d1);
    }
  }
  
  .platforms {
    .statistic-icon {
      background: linear-gradient(120deg, #66bb6a, #388e3c);
    }
  }
  
  .channels {
    .statistic-icon {
      background: linear-gradient(120deg, #ffa726, #f57c00);
    }
  }
  
  .messages {
    .statistic-icon {
      background: linear-gradient(120deg, #ab47bc, #7b1fa2);
    }
  }
}

.config-section {
  .config-header {
    margin-bottom: 25px;
    text-align: center;
    
    h2 {
      margin: 0 0 12px 0;
      font-size: 28px;
      color: #00695c;
      font-weight: 700;
      position: relative;
      display: inline-block;
      padding-bottom: 10px;
      
      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60px;
        height: 3px;
        background: linear-gradient(90deg, #00bcd4, #009688);
        border-radius: 3px;
      }
    }
    
    p {
      margin: 0;
      color: #78909c;
      font-size: 16px;
    }
  }
  
  .platform-cards {
    display: flex;
    gap: 25px;
    margin-bottom: 25px;
    flex-wrap: wrap;
    justify-content: center;
    
    .platform-card-wrapper {
      flex: 1;
      min-width: 350px;
      max-width: 400px;
    }
    
    .platform-card {
      height: 430px;
      border-radius: 15px;
      transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
      display: flex;
      flex-direction: column;
      position: relative;
      overflow: hidden;
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
      background: rgba(255, 255, 255, 0.85);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.5);
      
      &.active {
        border-color: #00bcd4;
        box-shadow: 0 10px 30px rgba(0, 188, 212, 0.25);
        transform: translateY(-5px);
      }
      
      &:hover:not(.active) {
        box-shadow: 0 12px 25px rgba(0, 0, 0, 0.12);
        transform: translateY(-3px);
      }
      
      .platform-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding: 20px 20px 15px 20px;
        border-bottom: 1px solid rgba(0, 150, 136, 0.1);
        background: linear-gradient(120deg, #e0f7fa 0%, #bbdefb 100%);
        
        .platform-title {
          display: flex;
          align-items: center;
          
          i {
            font-size: 24px;
            margin-right: 12px;
            color: #009688;
          }
          
          h3 {
            margin: 0;
            font-size: 20px;
            color: #00695c;
            font-weight: 700;
          }
        }
        
        .platform-switch {
          :deep(.el-switch__core) {
            width: 46px !important;
            height: 24px;
            border-radius: 12px;
            
            &::after {
              width: 20px;
              height: 20px;
            }
          }
          
          :deep(.el-switch.is-checked .el-switch__core::after) {
            left: 23px;
          }
        }
      }
      
      .platform-body {
        flex: 1;
        overflow-y: auto;
        overflow-x: hidden;
        //padding: 0 20px 130px 20px;
        padding-right: 15px;
        
        .config-form {
          height: 100%;
          display: flex;
          flex-direction: column;
          
          :deep(.el-form-item) {
            margin-bottom: 18px;
            
            &.is-required {
              .el-form-item__label::before {
                content: "*";
                color: #f56c6c;
                margin-right: 4px;
              }
            }
          }
          
          :deep(.el-form-item__label) {
            font-weight: 600;
            color: #455a64;
            padding-bottom: 18px;
          }
          
          :deep(.el-input-group__append) {
            padding: 0 15px;
            background: linear-gradient(120deg, #e0f7fa 0%, #bbdefb 100%);
            cursor: pointer;
            border: none;
            color: #00695c;
            font-weight: 500;
            transition: all 0.3s ease;
            
            &:hover {
              background: linear-gradient(120deg, #bbdefb 0%, #90caf9 100%);
            }
          }
          
          .form-placeholder {
            flex: 1;
          }
        }
      }
      
      .platform-footer {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        padding: 15px;
        border-top: 1px solid rgba(0, 150, 136, 0.1);
        background: rgba(255, 255, 255, 0.7);
        margin-top: auto;
        height: 140px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        
        .error-message {
          background: linear-gradient(120deg, #ffebee 0%, #ffcdd2 100%);
          color: #c62828;
          padding: 10px 15px;
          border-radius: 8px;
          margin-bottom: 15px;
          font-size: 14px;
          display: flex;
          align-items: center;
          box-shadow: 0 2px 6px rgba(198, 40, 40, 0.1);
          min-height: 60px;
          max-height: 80px;
          overflow: auto;
          
          i {
            margin-right: 10px;
            font-weight: bold;
            font-size: 18px;
            flex-shrink: 0;
          }
        }
        
        .error-placeholder {
          min-height: 60px;
          margin-bottom: 15px;
        }
        
        .save-button {
          text-align: center;
          flex-shrink: 0;
          margin-top: auto;
          
          :deep(.el-button) {
            padding: 12px 25px;
            font-size: 16px;
            font-weight: 600;
            border-radius: 8px;
            width: 60%;
            background: linear-gradient(120deg, #00bcd4, #009688);
            border: none;
            box-shadow: 0 4px 12px rgba(0, 150, 136, 0.25);
            
            &:hover {
              background: linear-gradient(120deg, #00acc1, #00897b);
              transform: translateY(-2px);
              box-shadow: 0 6px 15px rgba(0, 150, 136, 0.35);
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .config-section {
    .platform-cards {
      .platform-card-wrapper {
        min-width: 300px;
      }
    }
  }
}

@media (max-width: 992px) {
  .data-statistics {
    .el-col {
      margin-bottom: 20px;
    }
  }
  
  .config-section {
    .platform-cards {
      flex-direction: column;
      
      .platform-card-wrapper {
        min-width: 100%;
      }
    }
  }
}

// 修复横向滚动条问题
:deep(.el-card__body) {
  padding: 25px;
  box-sizing: border-box;
  overflow-x: hidden;
}

.form-help {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  cursor: pointer;
  
  .help-text {
    font-size: 14px;
    color: #888;
    margin-right: 8px;
    
    &:hover {
      color: #409eff;
      text-decoration: underline;
    }
  }
  
  .help-icon {
    color: #c0c4cc;
    cursor: pointer;
    font-size: 16px;
    
    &:hover {
      color: #409eff;
    }
  }
  
  &:hover {
    .help-text {
      color: #409eff;
      text-decoration: underline;
    }
    
    .help-icon {
      color: #409eff;
    }
  }
}

.qr-code-wrapper {
  text-align: center;
  padding: 20px;
  
  .qr-code-img {
    max-width: 100%;
    height: auto;
  }
  
  .qr-code-tip {
    margin-top: 15px;
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }
}

.bind-container {
  display: flex;
  align-items: center;
  gap: 15px;
  
  .bind-status {
    font-size: 14px;
    color: #c62828;
    
    &.bound {
      color: #67c23a;
    }
  }
}

.bound {
  background: linear-gradient(120deg, #67c23a, #409eff);
  border-color: #67c23a;
}
</style>